package com.ooono.factorytest.items;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.TextView;

import com.ooono.factorytest.R;
import com.ooono.factorytest.base.BaseActivity;

public class GSensorTestActivity extends BaseActivity implements SensorEventListener {

    private static final String TAG = "GSensorTestActivity";
    public static final String KEY = "gSensor";

    private SensorManager mSensorManager;
    private TextView gsensorXTv;
    private TextView gsensorYTv;
    private TextView gsensorZTv;

    @Override
    public int getTestTitle() {
        return R.string.gsensor_test_title;
    }

    @Override
    public String getTestKey() {
        return KEY;
    }

    @Override
    public int getContentLayout() {
        return R.layout.content_gsensor_test;
    }

    @Override
    public void initViews() {
        //获取Sensor服务
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        //获取G-Sensor的对象
        Sensor gsensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        //注册数据监听器，当有数据时会回调onSensorChanged方法
        mSensorManager.registerListener(this, gsensor, SensorManager.SENSOR_DELAY_NORMAL);

        gsensorXTv = findViewById(R.id.tv_gsensor_x);
        gsensorYTv = findViewById(R.id.tv_gsensor_y);
        gsensorZTv = findViewById(R.id.tv_gsensor_z);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if(event.sensor == null) {
            return;
        }
        //判断获取的数据类型是不是G-Sensor
        if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
            //获得数据
            gsensorXTv.setText("X: " + event.values[0] + " m/s²");
            gsensorYTv.setText("Y: " + event.values[1] + " m/s²");
            gsensorZTv.setText("Z: " + event.values[2] + " m/s²");
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSensorManager.unregisterListener(this);
    }
}
